﻿using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;

namespace Md.Api.DDD;
/// <summary>
/// JWT帮助类
/// </summary>
public class JwtHelp
{
    private static string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";

    /// <summary>
    /// 生成Token
    /// </summary>
    /// <param name="payload">不敏感的用户数据</param>
    /// <param name="expire">超时时间</param>
    /// <returns>string</returns>
    public static string SetJwtEncode(Dictionary<string, object> payload, double expire)
    {
        double _expire = (DateTime.UtcNow.AddSeconds(expire) - new DateTime(1970, 1, 1)).TotalSeconds;

        payload.Add("exp", _expire);

        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        var token = encoder.Encode(payload, secret);

        return token;
    }
    /// <summary>
    /// 解密token，获取到加密前的数据
    /// </summary>
    /// <param name="token">token</param>
    /// <returns>string</returns>
    public static string GetJwtDecode(string token)
    {
        string result;

        try
        {
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
            result = decoder.Decode(token, secret, verify: true); // token为之前生成的字符串
        }
        //表示令牌过期时引发的异常。
        catch (TokenExpiredException)
        {
            Console.WriteLine("Represents an exception thrown when when a token is expired.");
            result = "token is expired";
        }
        //表示当令牌不包含由点号分隔的3个令牌时引发的异常。
        catch (InvalidTokenPartsException)
        {
            Console.WriteLine("Represents an exception thrown when when a token doesn't consist of 3 delimited by dot parts.");
            result = "token doesn't consist of 3 delimited by dot parts";
        }
        //表示签名验证失败时引发的异常。
        catch (SignatureVerificationException)
        {
            Console.WriteLine("Represents an exception thrown when a signature validation fails.");
            result = "token signature validation fails";
        }
        //未知异常
        catch (Exception ex)
        {
            result = string.Format(@"token {0}", ex.Message);
        }

        return result;
    }
}

